/*
 * @Author: WeijianXu weijian.xu@unidt.com
 * @Date: 2024-02-20 12:03:53
 * @LastEditors: WeijianXu weijian.xu@unidt.com
 * @LastEditTime: 2024-02-27 16:46:36
 * @FilePath: \demo\bmap\test.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

// GL版命名空间为BMapGL
// 按住鼠标右键，修改倾斜角和角度
var map = new BMapGL.Map('allmap'); // 创建Map实例
var site = [120.21551, 30.253082];
var point = new BMapGL.Point(site[0], site[1]); // 创建点坐标
map.centerAndZoom(point, 12); // 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

map.setHeading(14.5); //设置地图旋转角度
map.setTilt(53); //设置地图的倾斜角度

var scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺
map.addControl(scaleCtrl);
var zoomCtrl = new BMapGL.ZoomControl(); // 添加缩放控件
map.addControl(zoomCtrl);
var cityCtrl = new BMapGL.CityListControl({
  anchor: BMAP_ANCHOR_BOTTOM_LEFT, // 控件位置，位于地图的左下角
  offset: new BMapGL.Size(10, 50), // 偏移，用于调整位置：x为10,y为50
  isOpen: true // 是否打开半透明效果，默认true
}); // 添加城市列表控件
map.addControl(cityCtrl);

/* 默认地图样式，版权信息无法消除 */
/* var copyrightCtrl = new BMapGL.CopyrightControl({
  anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
  offset: new BMapGL.Size(100, 10)
});
map.addControl(copyrightCtrl);
map.removeControl(copyrightCtrl); */

setMapStyle();
addContextMenu(); // 右键菜单

// 设置地图自定义样式
function setMapStyle() {
  const styleType = document.getElementById('customStyle').value;

  const types = {
    0: '',
    1: 'c4eb434f50b4939c47dd70c82584eb6a'
  };

  map.setMapStyleV2({
    styleId: types[styleType]
  });
}

// 设置地图类型
function setMapType() {
  map.setMapType(window[document.getElementById('maptype').value]);
}

// 设置地图中心点
function setCenterPoint() {
  const styleType = document.getElementById('centerPoint').value;

  var marker = null; // 创建标注
  if (styleType == '2') {
    marker = new BMapGL.Marker3D(point, 8000, {
      size: 50,
      shape: BMAP_SHAPE_CIRCLE,
      fillColor: '#00FF00',
      fillOpacity: 0.2
    });
  } else if (styleType == '1') {
    marker = new BMapGL.Marker(point);
  }

  if (marker == null) {
    return;
  }

  map.addOverlay(marker); // 将标注添加到地图中
  map.setCenter(marker.getPosition());

  marker.addEventListener('click', function() {
    // marker.setAnimation(BMAP_ANIMATION_BOUNCE); // BMapGL 动画当前1.0版本无效
    map.panTo(point); // 将该点居中显示，倾斜角度为0
  });
}

// 绘制行政区域边界
function drawBoundary() {
  const area = document.getElementById('boundary').value;
  if (!area) {
    return;
  }

  var bdary = new BMapGL.Boundary();
  bdary.get(area, function(rs) {
    //获取行政区域
    map.clearOverlays(); //清除地图上所有覆盖物
    var count = rs.boundaries.length; //行政区域的点有多少个
    if (count === 0) {
      alert('未能获取当前输入行政区域');
      return;
    }

    // 创建信息窗口对象
    var infoWindow = new BMapGL.InfoWindow('行政区域名称：' + area, {
      width: 200,
      height: 100,
      title: '行政区域信息'
    });

    var pointArray = [];
    for (var i = 0; i < count; i++) {
      var ply = new BMapGL.Polygon(rs.boundaries[i], {
        strokeWeight: 2,
        strokeColor: '#ff0000',
        fillColor: '#00ffff',
        fillOpacity: 0.4
      }); //建立多边形
      map.addOverlay(ply); //添加覆盖物
      pointArray = pointArray.concat(ply.getPath());

      ply.addEventListener('click', function() {
        map.openInfoWindow(infoWindow, ply.getBounds().getCenter());
      });
    }
    // map.setViewport(pointArray); //调整视野
  });
}

// 绘制3D行政区域边界
function draw3DBoundary() {
  const area = document.getElementById('boundary').value;

  var bdary = new BMapGL.Boundary();
  bdary.get(area, function(rs) {
    //获取行政区域
    map.clearOverlays(); //清除地图上所有覆盖物
    var count = rs.boundaries.length; //行政区域的点有多少个
    if (count === 0) {
      alert('未能获取当前输入行政区域');
      return;
    }

    for (var i = 0; i < count; i++) {
      let points = rs.boundaries[i].replace(/\s/g, '').split(';');
      let path = (points || []).map(point => {
        return new BMapGL.Point(...point.split(',').map(Number));
      });
      let prism = new BMapGL.Prism(path, 1000, {
        topFillColor: '#00ffff',
        topFillOpacity: 0.6,
        sideFillColor: '#ff0000',
        sideFillOpacity: 0.9
      });
      map.addOverlay(prism);

      prism.addEventListener('click', function(e) {
        console.log(e);
        getPos(prism.getBounds().getCenter(), area);
      });
    }
  });
}

/* 绘制覆盖物 */
function drawOverlay() {
  const type = document.getElementById('overlay').value;
  if (type === 'Poly') {
    drawPolygon();
  } else if (type === 'WestLakeGround') {
    drawGround();
  } else if (type === 'CustomOverlay') {
    drawCustomOverlay();
  }
}

// 绘制多边形折线图
function drawPolygon() {
  var p1 = new BMapGL.Point(site[0] - 0.12, site[1] - 0.06);
  var p2 = new BMapGL.Point(site[0], site[1] - 0.12);
  var p3 = new BMapGL.Point(site[0] + 0.12, site[1] - 0.06);
  var p4 = new BMapGL.Point(site[0] + 0.12, site[1] + 0.06);
  var p5 = new BMapGL.Point(site[0], site[1] + 0.12);
  var p6 = new BMapGL.Point(site[0] - 0.12, site[1] + 0.06);

  // 创建折线围成的多边形
  var polyline = new BMapGL.Polyline([p1, p2, p3, p4, p5, p6, p1], {
    strokeColor: '#0af',
    strokeWeight: 3,
    strokeOpacity: 0.5,
    strokeStyle: 'dashed'
  });
  map.addOverlay(polyline);

  var pg1 = new BMapGL.Point(site[0] - 0.08, site[1] - 0.04);
  var pg2 = new BMapGL.Point(site[0] + 0.08, site[1] - 0.04);
  var pg3 = new BMapGL.Point(site[0] + 0.08, site[1] + 0.04);
  var pg4 = new BMapGL.Point(site[0] - 0.08, site[1] + 0.04);

  // 创建多边形
  var polygon = new BMapGL.Polygon([pg1, pg2, pg3, pg4], {
    strokeColor: 'red',
    strokeWeight: 1,
    strokeOpacity: 0.5,
    fillColor: '#f00',
    fillOpacity: 0.2
  });
  map.addOverlay(polygon);
}

// 绘制西湖贴图
function drawGround() {
  map.clearOverlays();
  // 西湖区贴图坐标，开始点左上角，结束点右下角
  var pStart = new BMapGL.Point(120.133406, 30.269198);
  var pEnd = new BMapGL.Point(120.190341, 30.229359);
  var bounds = new BMapGL.Bounds(pStart, pEnd);
  var ground = new BMapGL.GroundOverlay(bounds, {
    opacity: 0.6,
    type: 'image',
    url: './west-lake.jpg'
  });
  map.addOverlay(ground);
  map.centerAndZoom(bounds.getCenter(), 14);
}

// 绘制自定义覆盖物
function drawCustomOverlay() {
  const count = Math.floor(Math.random() * 10) + 1;
  console.log(`着火点${count}(随机生成)`);
  for (let i = 1; i < count; i++) {
    const lng = site[0] + Math.random() * 0.5 - 0.25;
    const lat = site[1] + Math.random() * 0.5 - 0.25;
    const customOverlay = new BMapGL.CustomOverlay(createDom, {
      point: new BMapGL.Point(lng, lat),
      opacity: 0.5,
      map: map,
      offsetY: -10,
      properties: {
        title: `着火点${i}(随机生成)`,
        size: '100'
      },
      enableMassClear: true, // 是否能被统一清除掉覆盖物
    });
    map.addOverlay(customOverlay);
  
    customOverlay.addEventListener('click', function(e) {
      console.log(e);
      getPos(customOverlay.getPoint(), `着火点${i}(随机生成)`);
    });
  }
}
function createDom(feature) {
  const img = document.createElement('img');
  img.src = 'https://bj.bcebos.com/v1/mapopen-pub-jsapigl/assets/images/fire.gif';
  img.style.width = '80px';
  img.style.height = '240px';
  img.draggable = false;
  return img;
}


function reset() {
  map.reset();
}
function clearAll() {
  map.clearOverlays(); // 清除地图上所有覆盖物
}

// 获取坐标
function getPos(point, area) {
  // var point = new BMapGL.Point(e.point.lng, e.point.lat);
  var label = new BMapGL.Label(`您点击了: ${area}`, {
    position: point,
    offset: new BMapGL.Size(10, 20)
  });
  label.setStyle({
    color: '#fff',
    fontSize: '12px',
    height: '20px',
    lineHeight: '20px',
    fontFamily: '微软雅黑',
    backgroundColor: '#ee8833',
    border: '1px solid #ee8833',
    textAlign: 'center'
  });
  map.addOverlay(label);
}

// 右键菜单
function addContextMenu() {
  var menuItems = [
    {
      text: '删除所有标注',
      callback: function() {
        clearAll();
      }
    },
    {
      text: '重置地图',
      callback: function() {
        reset();
      }
    },
    {
      text: '放大',
      callback: function () {
        map.zoomIn();
      }
    },
    {
      text: '缩小',
      callback: function () {
        map.zoomOut();
      }
    }
  ];
  var menu = new BMapGL.ContextMenu();
  for (var i = 0, l = menuItems.length; i < l; i++) {
    var item = menuItems[i];
    menu.addItem(new BMapGL.MenuItem(item.text, item.callback, {
      width: 100,
      id: 'menu' + i,
    }));
  }
  map.addContextMenu(menu);
}
